package com.bahehe.taoyunabus;



import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;




import com.bahehe.taoyunabus.wheelview.OnWheelChangedListener;
import com.bahehe.taoyunabus.wheelview.OnWheelScrollListener;
import com.bahehe.taoyunabus.wheelview.WheelView;
import com.bahehe.taoyunabus.db.dbMyFavor;
import com.bahehe.taoyunabus.wheelview.ArrayWheelAdapter;
import com.kuad.KuBanner;
import com.kuad.PublicBeen;



import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BusRouteTime extends Activity {

	private dbMyFavor dbHelper;
	
	private final static String TAG = "BusRouteTime";
	private final static String BUS_NAME="bus_name";
	private final static String BUS_NUMBER="bus_num";
	private final static String BUS_ROUTEID="bus_id";
	
	private String[] defaultgroup;
	private int groupsize = 0;
	private ArrayList lstGroup = new ArrayList<String>();
	
	private Button btn;
	private Dialog dialog;
	
	private Button mManualUpdateGoto;
	private Button mManualUpdateGoback;
	
	private boolean IsResetADLoop=false;
  	private Handler timer=new Handler();
  	private Random RandomGen=null;
  	private int LongClickTick=0;
  	private KuBanner kuView;
	
	private final static String URL_GET_BUSSTOP_TIME = "http://124.199.77.90/Taoyuan/aspx/dyBus/BusXMLLine.aspx?Mode=2&Line=";
	
	private final static String GO = "&GoBack=1";
	private final static String BACK = "&GoBack=2";
	
	private final static String Location_TW = "&Lang=";
	private final static String Location_EN = "&Lang=En";
	
	private ArrayList<String> saveNum = new ArrayList<String>();
	private ArrayList<String> saveBusStopName = new ArrayList<String>();
	private ArrayList<String> saveBusTime = new ArrayList<String>();
	private ArrayList<String> saveStationLongtude = new ArrayList<String>();
	private ArrayList<String> saveStationLatitude= new ArrayList<String>();
	private ArrayList<String> saveBusPlate= new ArrayList<String>();
	private ArrayList<String> saveBusLongtude= new ArrayList<String>();
	private ArrayList<String> saveBusLatitude= new ArrayList<String>();
	//private final static String URL_GET_BUSSTOP_POS = "http://hisatisfy.hccg.gov.tw/eBusHC/Map/time/ws/getRoadLine.aspx?hash=060089367388473036&run_id=";
	
	private String strBusName;
	private String strBusNumber;
	//private String strBusRouteID;
	
	private BaseAdapterBusTime bustimeAdapter;
	private ListView mListBusTime;
	private  long dateTaken;
	
	//private ArrayList<String> saveNum = new ArrayList<String>();

	
	private ArrayList<SearchResults> searchResults = null;
	private String selBusStopName;
	private String selgroup;
	
	private static final String DATABASE_NAME = "hsinchubus.db";	//資料庫名稱
	private static final int DATABASE_VERSION = 1;	//資料庫版本
	private static final String TABLE_NAME = "myfavor";
	private ProgressDialog progressDialog;
	
	private boolean wheelScrolled = false;
	
	private ProgressDialog mProgressDialog ;
	
	private String busstop;
	private String group;
	private String routeName ;
	private String routeID ;
	private String routeNumber;
	
	private static String mLocation;
	
	private String RouteNum;
	
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		
		Log.i(TAG,"onCreate() ");
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
        setContentView(R.layout.bustime);
        
        //dbHelper = new dbMyFavor(this,DATABASE_NAME,null,DATABASE_VERSION);
        
   	 	mManualUpdateGoto=(Button)findViewById(R.id.btnManualUpdateGoto);
   	 	mManualUpdateGoback=(Button)findViewById(R.id.btnManualUpdateGoback);
        
   	 	InitAD();
//        KuBanner banner = (KuBanner)findViewById(R.id.kuadview);
//        banner.setAPID("000000aBO");
        
        if(haveInternet()==false){
        	NotificationManager nManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        	Notification nMsg = new Notification(android.R.drawable.ic_dialog_alert, getResources().getString(R.string.app_name), System.currentTimeMillis());
        	PendingIntent pIntent = PendingIntent.getActivity(this,0,new Intent(this, MainActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
        	nMsg.setLatestEventInfo(this,getResources().getString(R.string.app_name), getResources().getString(R.string.network_state),pIntent);
        	nManager.notify(0, nMsg);
        	finish();
        }
        
        Bundle bundle = this.getIntent().getExtras();
		strBusName = bundle.getString(BUS_NAME);
		//strBusRouteID = bundle.getString(BUS_ROUTEID);
		strBusNumber = bundle.getString(BUS_NUMBER);
		
		Log.i(TAG,"Bus Name = "+strBusName);
		//Log.i(TAG,"Bus RouteID = "+strBusRouteID);
		Log.i(TAG,"Bus Number = "+strBusNumber);
		
		mLocation= getResources().getConfiguration().locale.getLanguage();
		
		TextView txtTitle = (TextView)findViewById(R.id.txtTitle);
		
		txtTitle.setText(strBusNumber + ":" +strBusName );
		
		mListBusTime = (ListView)findViewById(R.id.listViewBusTime);
		
		 dateTaken = System.currentTimeMillis();  
         if (dateTaken != 0) {  
             String datetime = DateFormat.format("kk:mm:ss", dateTaken).toString();  
             TextView curTime =(TextView)findViewById(R.id.tvCurrentTime);
             curTime.setText(getResources().getString(R.string.getdatatime) + datetime);
         }  
		
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setTitle("取得目前公車動態資訊中");
		mProgressDialog.setMessage("請稍候片刻");
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.show();
		
		if(mLocation.equals("zh"))
			RouteNum = strBusNumber.substring(0, strBusNumber.length()-1);
		else
			RouteNum = strBusNumber.substring(0, strBusNumber.length()-5);
		try{
			UpdateBusLine(RouteNum, GO);
		}catch (Exception ex){
			ex.printStackTrace();
		}
	
		try {
	        	searchResults = GetSearchResults();          
	        	bustimeAdapter = new BaseAdapterBusTime(BusRouteTime.this, searchResults);
	        	mListBusTime.setAdapter(bustimeAdapter);   
	        	mListBusTime.setOnItemClickListener(BusTimeClickListener);
	        	//mListBusTime.setOnItemSelectedListener(BusTimeSelectedListener);
	        	mListBusTime.setOnItemLongClickListener(BusTimeLongClickListener);
	        	mListBusTime.setOnCreateContextMenuListener(BusTimeContectClickListener);
		} catch (Exception e) {
				// TODO: handle exception
		}
		

	    Thread thread = new Thread(new GetBusLineData());
	    thread.start();
	    
	    mManualUpdateGoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try{
					UpdateBusLine(RouteNum, GO);
					searchResults = GetSearchResults();          
		        	bustimeAdapter = new BaseAdapterBusTime(BusRouteTime.this, searchResults);
		        	mListBusTime.setAdapter(bustimeAdapter);   
		        	mListBusTime.setOnItemClickListener(BusTimeClickListener);
		        	mListBusTime.setOnItemLongClickListener(BusTimeLongClickListener);
		        	mListBusTime.setOnCreateContextMenuListener(BusTimeContectClickListener);
		        	
		        	bustimeAdapter.notifyDataSetChanged();
		        	Thread thread = new Thread(new GetBusLineData());
		     	    thread.start();
				}catch (Exception ex){
					ex.printStackTrace();
				}
				
			}
	    
	    });
	    
	    mManualUpdateGoback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try{
					UpdateBusLine(RouteNum, BACK);
					searchResults = GetSearchResults();          
		        	bustimeAdapter = new BaseAdapterBusTime(BusRouteTime.this, searchResults);
		        	mListBusTime.setAdapter(bustimeAdapter);   
		        	mListBusTime.setOnItemClickListener(BusTimeClickListener);
		        	mListBusTime.setOnItemLongClickListener(BusTimeLongClickListener);
		        	mListBusTime.setOnCreateContextMenuListener(BusTimeContectClickListener);
		        	bustimeAdapter.notifyDataSetChanged();
		        	Thread thread = new Thread(new GetBusLineData());
		     	    thread.start();
				}catch (Exception ex){
					ex.printStackTrace();
				}
				
			}
	    
	    });
        
	}
	
	  public void InitAD()
	    {
	    	if(RandomGen == null)
	    		RandomGen=new Random(System.currentTimeMillis()/1000);
	    	
	    	if(kuView == null)
	    		kuView=(KuBanner )findViewById(R.id.kuadview);
	    	
			kuView.setAPID("000000aBO");
			kuView.appStart();
			kuView.setOnLongClickListener(ADLongClickListener);
	    }
	    //----------------------------------------------------------
	    private void ResetAD()
	    {
	    	try
	    	{
	    		LinearLayout ad_layout=(LinearLayout)findViewById(R.id.ad_layout);        	
	        	if(kuView != null)
	        	{
	        		ad_layout.removeView(kuView);
	        		Thread.sleep(200);
	        	}
	        	
	        	kuView=new KuBanner(this);
	        	InitAD();
	        	ad_layout.addView(kuView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));        	
	    	}
	    	catch(Exception e){}
	    }
	    //-------------------------------------------------------------
	    OnLongClickListener ADLongClickListener=new OnLongClickListener()
	    { 
	        public boolean onLongClick(View v)
	        {
	        	LongClickTick++;
	        	
	        	if(LongClickTick > 1)
	        	{
	        		IsResetADLoop=true;
	            	timer.postDelayed(ResetADimer, 500);
	        	}
	        	
	            return true;
	        }
	    };
	    //----------------------------------------------------------
	    private Runnable ResetADimer = new Runnable()
	    {
	    	public void run()
	    	{
	    		ResetAD();
	    		if(IsResetADLoop)
	    			timer.postDelayed(ResetADimer, 1800+RandomGen.nextInt(150)*100);	
	    	}
	    };

	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.i(TAG,"onPause()");
		super.onPause();
	}



	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		Log.i(TAG,"onRestart()");
		super.onRestart();
	}



	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.i(TAG,"onResume()");
		super.onResume();
	}



	@Override
	protected void onStart() {
		Log.i(TAG,"onStart()");
		super.onStart();
	}



	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		Log.i(TAG,"onStop()");
		super.onStop();
	}


	
	private AdapterView.OnItemLongClickListener BusTimeLongClickListener = new AdapterView.OnItemLongClickListener(){

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			Object o = mListBusTime.getItemAtPosition(arg2);
			SearchResults fullObject = (SearchResults)o;
			Log.i(TAG,"getBusname=" +fullObject.getRoute_name() );
			Log.i(TAG,"getBustime=" +fullObject.getBustime() );
			
			selBusStopName = fullObject.getRoute_name();
			
			return false;
		}

//		@Override
//		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
//				long arg3) {
//			// TODO Auto-generated method stub

			

		
	};
	
	private AdapterView.OnItemClickListener BusTimeClickListener = new AdapterView.OnItemClickListener(){

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			// TODO Auto-generated method stub
//			Object o = mListBusTime.getItemAtPosition(position);
//			SearchResultsBusTime fullObject = (SearchResultsBusTime)o;
//			Log.i(TAG,"getBusname=" +fullObject.getBusname() );
//			Log.i(TAG,"getBustime=" +fullObject.getBustime() );
//			
//			selBusStopName = fullObject.getBusname();
			//fullObject.getRoute_number()
		//	Bundle bundle = new Bundle();
		//	bundle.putString(BUS_NAME, fullObject.getRoute_name());
		//	bundle.putString(BUS_ROUTEID, fullObject.getRoute_id());
		//	bundle.putString(BUS_NUMBER,fullObject.getRoute_number() );
			
		//	Intent intent = new Intent(BusInfo.this,BusRouteTime.class);
	    //	intent.putExtras(bundle);
	    //	startActivity(intent);
		}
		
	};
	
	
	 private OnCreateContextMenuListener BusTimeContectClickListener= new OnCreateContextMenuListener() {  
         
         @Override  
         public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
             menu.setHeaderTitle("設置");     
             menu.add(0, 0, 0, "設置常用路線");  
             menu.add(0, 1, 0, "設置到站通知");     
         }
    
         
     };
     
 	public void GetGroupsinDB(){
 		
 		SQLiteDatabase  db = this.dbHelper.getReadableDatabase();
 		try {
 	 		Cursor cursor = db.query(BusRouteTime.TABLE_NAME, new String[] {
 	                "groups"
 	        }, null, null, "groups", null,null);
 	 		
 	 		if(lstGroup!=null)
 	 			lstGroup.clear();
 	 		
 	 		//StringBuilder data = new StringBuilder();
 	 		while (cursor.moveToNext()) {
 	           String strgroup = cursor.getString(0).toString();
 	           lstGroup.add(strgroup);
 	        }
		} catch (Exception e) {
			Log.e(TAG,"Error->"+e.getMessage());
		}finally{
			db.close();
		}
 	
 		 
	}
     
     
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
	
		
		
		switch(item.getItemId()){
				case 0:
					
					GetGroupsinDB();
					
				try {
					if(lstGroup!=null){
						groupsize = lstGroup.size();
						defaultgroup = new String[groupsize];
						
						defaultgroup[0] = "新增群組";
						for(int i=1;i<groupsize;i++){
							defaultgroup[i] = lstGroup.get(i).toString();
							
						}
					}
				
//					for(int k=0;k<defaultgroup.length;k++){
//						System.out.println(defaultgroup[k]);
//					}
					
					final List<String> list_group = Arrays.asList(defaultgroup);
					

					dialog = new Dialog(this);
					dialog.setTitle("加入此站牌於以下群組");

					LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
					View view = inflater.inflate(R.layout.wheelview, null);
					

					final WheelView wv_group = (WheelView)view.findViewById(R.id.groupview);
					wv_group.setAdapter(new ArrayWheelAdapter<String>(defaultgroup));
					wv_group.setCyclic(true);
					wv_group.setVisibleItems(3);
					wv_group.setCurrentItem(0);
					wv_group.TEXT_SIZE = 28;
					
					selgroup = defaultgroup[0];
					
					// Wheel scrolled listener
					OnWheelScrollListener scrolledListener = new OnWheelScrollListener()
						{
							@Override
							public void onScrollingStarted(WheelView wheel) {
								// TODO Auto-generated method stub
								wheelScrolled = true;
							}

							@Override
							public void onScrollingFinished(WheelView wheel) {
								// TODO Auto-generated method stub
								wheelScrolled = false;
				//				updateStatus();
							}
						};
					
					
	

					OnWheelChangedListener wheelListener_Group = new OnWheelChangedListener() {

						@Override
						public void onChanged(WheelView wheel, int oldValue,
								int newValue) {
							// TODO Auto-generated method stub
							//int wheelPos = newValue + 1;
							
							selgroup = defaultgroup[wv_group.getCurrentItem()]; 
							Log.i(TAG,selgroup);
							
						}
						
					};
					
					wv_group.addChangingListener(wheelListener_Group);
					wv_group.addScrollingListener(scrolledListener);
					

					Button btn_sure = (Button) view.findViewById(R.id.btn_sure);
					Button btn_cancel = (Button) view
							.findViewById(R.id.btn_cancel);
					
					btn_sure.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							
							if(selgroup.equals("新增群組")){
   LayoutInflater factory=LayoutInflater.from(BusRouteTime.this); 
								   
								   
				                 
				                   final View DialogView=factory.inflate(R.layout.addnewgroup, null);  
				  				   final EditText addGroup = (EditText)DialogView.findViewById(R.id.editAddNewgroup);
				  				   
				  				   
//							      if(addGroup==null)
//							    		Log.i(TAG," onClick addGroup is NULL");
//							      if(DialogView==null)
//							    	  Log.i(TAG," onClick DialogView is NULL");
							      
								   AlertDialog dlg=new AlertDialog.Builder(BusRouteTime.this)  
					                .setTitle("輸入群組名稱")  
					                .setView(DialogView)//設置自定義對話框樣式  
					                .setPositiveButton("確定", new DialogInterface.OnClickListener() {//設置監聽事件  
					                      
					                    @Override  
					                    public void onClick(DialogInterface dialog, int which) {  
					                    	
					                    	if(addGroup==null){
					                    		Log.i(TAG,"addGroup is NULL");
					                    		return;
					                    	}					             					                    	
					                        // 輸入完成後點擊「確定」開始登錄  
					                        progressDialog=ProgressDialog.show(BusRouteTime.this, "請稍等...", "正在處理...",true);  
					                        new Thread()  
					                        {  
					                            public void run()  
					                            {  
					                                try  
					                                {  
					                                	busstop = selBusStopName;
					    								group = addGroup.getText().toString();
					    								routeName = strBusName;
					    						//		routeID = strBusRouteID;
					    								routeNumber = strBusNumber;
					    								
					    								System.out.println("busstop=" + busstop);
					    								System.out.println("selgroup=" + group);
					    								System.out.println("routeName=" + routeName);
					    								System.out.println("routeID=" + routeID);
					    								System.out.println("routeNumber=" + routeNumber);

					                                	addBusStop2Group(group, routeID, routeName, routeNumber,busstop);
					                                    sleep(3000);  
					                                }catch(Exception e)  
					                                {  
					                                    e.printStackTrace();  
					                                }finally  
					                                {  
					                                  
					                                	progressDialog.dismiss();  
					                                }  
					                            }  
					                        }.start();  
					                    }  
					                }).setNegativeButton("取消",//設置取消按鈕  
					                    new DialogInterface.OnClickListener() {  
					                          
					                        @Override  
					                        public void onClick(DialogInterface dialog, int which) {  
					                            //點擊取消後退出程序  
					                        	//BusRouteTime.this.finish();
					                        	
					                        }  
					                    }).create();//創建對話框  
					                dlg.show();//顯示對話框  															 								
							}else {
								busstop = selBusStopName;
								group = selgroup;
								routeName = strBusName;
						//		routeID = strBusRouteID;
								routeNumber = strBusNumber;
								
								System.out.println("busstop=" + busstop);
								System.out.println("selgroup=" + group);
								System.out.println("routeName=" + routeName);
								System.out.println("routeID=" + routeID);
								System.out.println("routeNumber=" + routeNumber);

								addBusStop2Group(group, routeID, routeName, routeNumber,busstop);
								
							}
						 
							dialog.dismiss();
						}
					});

					btn_cancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
						//	Toast.makeText(BusRouteTime.this, "此功能尚未加入", Toast.LENGTH_LONG).show();
							dialog.dismiss();
						}
					});
					
					
					
					dialog.setContentView(view);
					dialog.show();
					
				} catch (Exception e) {
					Log.e(TAG,"Error->"+e.getMessage());
				}
					
					
					break;
				case 1:
					Toast.makeText(BusRouteTime.this, "此功能尚未加入", Toast.LENGTH_LONG).show();
					break;
		}
		return super.onContextItemSelected(item);
	}
	
	private void addBusStop2Group(String group,String routeID,String routeName,String routeNumber,String busstop) {
        // 新增一筆 ActionLog，因為是新增，所以使用寫入模式
        SQLiteDatabase db = this.dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("groups", group);
        values.put("busstop", busstop);
        values.put("route_id", routeID);
        values.put("route_name", routeName);
        values.put("route_number", routeNumber);

        db.insert(BusRouteTime.TABLE_NAME, null, values);
        db.close();
  //      onCreate(savedInstanceState);
        
    }

	private void UpdateBusLine(String routeNumber, String GoBack){		
		String strUri;
		if(mLocation.equals("zh")){
			strUri = URL_GET_BUSSTOP_TIME + routeNumber + GoBack + Location_TW;
		}else {
			strUri = URL_GET_BUSSTOP_TIME + routeNumber + GoBack + Location_EN;
		}
		
		Log.i(TAG,"URL=" + strUri);
		HttpPost httpPost = new HttpPost(strUri);
    	HttpClient httpClient = new DefaultHttpClient();
    	
    	
    	saveNum.clear();
    	saveBusStopName.clear();
    	saveBusTime.clear();
    	saveStationLongtude.clear();
    	saveStationLatitude.clear();
    	
    	
    	
    	String[] strTimes;
	    String[] strNewTimes;
    	
    	try{
			HttpResponse httpResponse = httpClient.execute(httpPost);
				if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
					String strResult = EntityUtils.toString(httpResponse.getEntity());
					Log.i(TAG,strResult);
					String[] strAllLines = strResult.split("\\|");
					//int i = 1;
					for(String line:strAllLines){
	    			    if(line.indexOf(".") > 0 && line.indexOf("-") <0 && line.indexOf("@") <0){
	    				String[] strLines = line.split("\\,");
		    				saveNum.add(strLines[0]);
		    				saveBusStopName.add(strLines[2]);
		    				saveStationLongtude.add(strLines[4]);
		    				saveStationLatitude.add(strLines[5]);
	    			    }    			        
	    			    else if((line.indexOf(".") < 0 && line.indexOf("-") <0 && line.indexOf("@") <0)){
		    				line = line.replace(",", getResources().getString(R.string.leavestation));    				
		    				strTimes = line.split("\\,");
		    				strNewTimes = new String[strTimes.length];
		    				for(int i=0;i<strTimes.length;i++){
		    					if(mLocation.equals("zh"))	{
		    						if(strTimes[i].length() >=4){	      					
			        				      strNewTimes[i] = strTimes[i].substring(0, strTimes[i].length()-3);}		   
		    						else{
		    							 strNewTimes[i] = strTimes[i];
		    							 
		    						}
			        				      
		    				}else {
			    					if(strTimes[i].length() >=6){		      					
			        				       strNewTimes[i] = strTimes[i].substring(0, strTimes[i].length()-7);
			        				   		System.out.println(strNewTimes[i]);
			        				       }		   
		 						    else{
		 						    	strNewTimes[i] = strTimes[i];
		 						    
		 						    }
			        				       
		    				 }
		    				}
		        	
		    				for(String strTime: strNewTimes) {
				    			    if(strTime.equals("0")){		    		    	
				    				    saveBusTime.add(getResources().getString(R.string.arriivetation));
								    }else  if(strTime.indexOf(":") > 0){
				    					saveBusTime.add(strTime);
				    			   }else  if(strTime.indexOf(getResources().getString(R.string.leave)) == 0){
				    				   	saveBusTime.add(strTime);
								   }else 
								    	saveBusTime.add(strTime+getResources().getString(R.string.min));
		    				}
	    			    }
		    			    }
	    				}			
    	}catch(Exception ex)
    	{
    		
    	}finally{
    		System.out.println(saveBusStopName);
    		System.out.println(saveBusTime);
    	}
    	

	}
	
	private ArrayList<SearchResults> GetSearchResults(){
	     ArrayList<SearchResults> results = new ArrayList<SearchResults>();
	     try {
	         if(saveBusStopName!=null && saveBusTime!=null){
		    	 for(int i=0; i<saveBusStopName.size();i++){
		    		 SearchResults sr = new SearchResults();
		    		 sr.setRoute_name(saveBusStopName.get(i).toString());
		    		 sr.setBustime(saveBusTime.get(i).toString());		    		 
				     results.add(sr);
		    	 }
		    	     	 
		     }
		} catch (Exception e) {
			// TODO: handle exception
		}
	
	 
	     return results; 	 
	     
   }
	
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			mProgressDialog.dismiss();
		}
	};
	
	private class GetBusLineData implements Runnable {

		@Override
		public void run() {
			try{			
				Thread.sleep(3000);
			}
			catch(InterruptedException e){
				e.printStackTrace();
			}
			mHandler.sendEmptyMessage(0);
		}
		
	}
	
	private boolean haveInternet()
    {
    	boolean result = false;
    	ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    	NetworkInfo info=connManager.getActiveNetworkInfo();
    	if (info == null || !info.isConnected())
    	{
    		result = false;
    	}
    	else 
    	{
    		if (!info.isAvailable())
    		{
    			result =false;
    		}
    		else
    		{
    			result = true;
    		}
    	}
    	
    	return result;
    }
	
}
